<template>
  <div class="container">
    <el-form
      ref="form"
      :rules="rules"
      :model="form"
      label-width="120px"
      label="right"
    >
      <div class="header">
        <el-form-item label="菜品名称：" prop="name">
          <el-input v-model="form.name" placeholder="请填写菜品名称"></el-input>
        </el-form-item>
        <el-form-item label="菜品分类：" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择菜品分类">
            <el-option
              v-for="item in categoryOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </div>
      <el-form-item label="菜品价格：" prop="price">
        <el-input
          v-model.number="form.price"
          placeholder="请设置菜品价格"
        ></el-input>
      </el-form-item>
      <el-form-item label="口味做法配置：">
        <el-button type="primary" icon="el-icon-plus">新建菜品</el-button>
      </el-form-item>
      <el-form-item label="菜品图片：" prop="image">
        <el-upload
          class="avatar-uploader"
          action="#"
          :show-file-list="false"
          :http-request="handleUpload"
        >
          <img
            v-if="form.imageUrl"
            :src="`${env}/common/download?name=${form.imageUrl}`"
            class="avatar"
          />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="菜品描述：">
        <el-input
          class="desc-size"
          type="textarea"
          v-model="form.description"
          :maxlength="200"
          placeholder="菜品描述，最长200字"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="$router.push({ name: 'Dish' })">取消</el-button>
        <el-button type="primary" @click="onSubmit">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getDish, changeStatus, addDish } from "@/api/dish";
import { getCategory } from "@/api/category";
import { upload } from "@/api/common";
export default {
  computed: {
    isEdit() {
      return this.$route.query.isEdit === "true";
    },
    id() {
      return this.$route.query.id;
    },
  },
  created() {
    this.fetchCategoryOptions();
    if (this.isEdit) {
      getDish(this.id).then((res) => {
        this.form = res.data;
      });
    }
  },
  data() {
    return {
      env: process.env.VUE_APP_BASE_API,
      categoryOptions: [],
      // 提交的数据
      form: {
        name: "",
        code: "",
        flavors: [],
        categoryId: "",
        price: "",
        image: "",
        imageUrl: "",
        description: "",
      },
      // 验证规则对象
      rules: {
        name: [
          {
            required: true,
            message: "请填写菜品名称",
            trigger: ["blur", "change"],
          },
        ],
        categoryId: [
          {
            required: true,
            message: "请选择菜品分类",
            trigger: ["change"],
          },
        ],
        price: [
          {
            required: true,
            message: "请设置菜品价格",
            trigger: ["blur", "change"],
          },
          {
            pattern: /^\d+(\.\d{1,2})?$/,
            message: "菜品价格格式只能为数字，且最多保留两位小数",
            trigger: ["blur", "change"],
          },
        ],
        image: [
          {
            required: true,
            message: "请选择图片",
            trigger: ["blur", "change"],
          },
        ],
      },
    };
  },
  methods: {
    handleUpload(file) {
      const formdata = new FormData();
      formdata.append("file", file.file);
      upload(formdata).then((res) => {
        this.form.imageUrl = res.data;
      });
    },
    fetchCategoryOptions() {
      getCategory({ type: "1" })
        .then((response) => {
          this.categoryOptions = response.data;
        })
        .catch((error) => {
          console.error("获取分类列表失败:", error);
          this.$message.error("获取分类列表失败");
        });
    },
    onSubmit() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          if (this.isEdit) {
            await changeStatus(this.form);
            this.$message.success("修改菜品成功");
          } else {
            await addDish(this.form);
            this.$message.success("添加菜品成功");
          }
          this.$router.push({ name: "Dish" });
        } else {
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  padding: 55px;
  .header {
    display: flex;
    // justify-content: space-between;
  }
  .el-form-item {
    width: 400px;
    .el-input {
      width: 260px;
    }
    .desc-size {
      width: 670px;
    }
    .el-select {
      width: 260px;
    }
    .avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
      border-color: #409eff;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
  }
}
</style>
